package io.renren.modules.test.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.jayway.jsonpath.JsonPath;
import io.renren.modules.test.service.ElasticsearchService;
import io.renren.modules.test.utils.HttpClientUtil;
import net.minidev.json.JSONArray;
import org.omg.CORBA.OBJ_ADAPTER;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ElasticsearchServiceImpl implements ElasticsearchService {
    @Override
    public Map<String,Integer> getElasticsearchByTime(String start, String end, String size){
        Map<String,String> map=new HashMap<String, String>();
        map.put("kbn-version","6.7.0");
        map.put("Content-Type","application/json");
        String paramJson="{\n" +
                "  \"size\": "+size+",\n" +
                "  \"from\": 0,\n" +
                "  \"query\": {\n" +
                "    \"bool\": {\n" +
                "      \"must\": [\n" +
                "        {\n" +
                "          \"range\": {\n" +
                "            \"@timestamp\": {\n" +
                "              \"gte\": \""+start+"\",\n" +
                "              \"lte\": \""+end+"\",\n" +
                "               \"format\": \"yyyy-MM-dd HH:mm:ss\"\n" +
                "            }\n" +
                "          }\n" +
                "        }\n" +
                "      ]\n" +
                "    }\n" +
                "  },\n" +
                " \"sort\": [\n" +
                "    {\n" +
                "      \"@timestamp\": {\n" +
                "        \"order\": \"desc\"\n" +
                "      }\n" +
                "    }\n" +
                "  ]\n"+
                "}";
        return analysisElasticsearchLog(HttpClientUtil.doPostTestFourWithHeader("http://kibana.biz.cloud.net/api/console/proxy?path=_search&method=POST",paramJson,map));
    }

    public Map<String,Integer>  analysisElasticsearchLog(String log){
        List<LinkedHashMap> systemUseLogs = JsonPath.read(log, "$.hits.hits");
        HashMap<String,Integer> systemUseMap=new HashMap<String,Integer>();
        for(LinkedHashMap systemUseLog:systemUseLogs){
            LinkedHashMap messageJson= (LinkedHashMap) systemUseLog.get("_source");
            String host=((LinkedHashMap)messageJson.get("beat")).get("hostname").toString();
            if(systemUseMap.containsKey(host)){
                systemUseMap.put(host,systemUseMap.get(host)+1);
            }else{
                systemUseMap.put(host,1);
            }
        }
        Random e=new Random();
        systemUseMap.put("测试数据1",e.nextInt(200));
        systemUseMap.put("测试数据2",e.nextInt(200));
        systemUseMap.put("测试数据3",e.nextInt(200));
        return systemUseMap;
    }
}
